package com.etc.user.controller;

import com.etc.entity.FlashOrder;
import com.etc.entity.Orders;
import com.etc.entity.po.FlashGoodsMessagePo;
import com.etc.rabbitmq.FlashMessage;
import com.etc.rabbitmq.MQSender;
import com.etc.redis.FlashGoodsKey;
import com.etc.redis.RedisService;
import com.etc.result.CodeMsg;
import com.etc.result.Result;
import com.etc.service.FlashGoodsService;
import com.etc.service.ProvinceService;
import com.etc.vo.FlashGoodsDetialMessageVo;
import com.etc.vo.OrderMessageVo;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 文件名:com.etc.user.controller.FlashGoodsController
 * 描述：秒杀商品控制器
 * 作者:吴仕泉
 * 时间:2019/5/24 20:04
 */
@Controller
@RequestMapping("flashgoods.action")
public class  FlashGoodsController {

    @Autowired
    FlashGoodsService flashGoodsService;

    @Autowired
    RedisService redisService;

    @Autowired
    ProvinceService provinceService;

    @Autowired
    MQSender mqSender;

    //标记每种商品库存状态 Y:标记为还有库存，N ：库存为空
   // HashMap<Integer,String> flashGoodsState = new HashMap<>();

    //根据秒杀活动ID获取该活动的所有商品信息
    @RequestMapping("showFlashGoodsByFlashSaleId")
    @ResponseBody
    public Result<FlashGoodsMessagePo> showFlashGoodsByFlashSaleId(@RequestParam(value = "flashSaleId") Integer flashSaleId){
        List<FlashGoodsMessagePo> listpo = flashGoodsService.selectFlashSaleGoodsMessageBySaleId(flashSaleId);
       // System.out.println("进来了"+flashSaleId);
        if(listpo == null || listpo.size()<=0){
            return Result.error(CodeMsg.FLASH_GOODS_MESSAGE_NULL);
        }

        //标记商品库存状态
//        String state = flashGoodsState.get(flashSaleId);
//        if(state == null){
//           Integer num =  redisService.get(FlashGoodsKey.getFlashGoodsStock,String.valueOf(flashSaleId),Integer.class);
//           if(num!=null&&num>0){
//               flashGoodsState.put(flashSaleId,"Y");
//           }else{
//               flashGoodsState.put(flashSaleId,"N");
//           }
//
//        }

      //  listpo.forEach(System.out::println);
        return Result.success(listpo);
    }

    //根据秒杀商品ID查询该秒杀商品的具体信息
    @RequestMapping("showFlashGoodsMessage")
    @ResponseBody
    public Result<FlashGoodsDetialMessageVo> showFlashGoodsMessageByFlashGoodsId(@RequestParam(value = "flashGoodsId") Integer flashGoodsId){
        FlashGoodsDetialMessageVo mv = flashGoodsService.selectFlashGoodsDetialMeaasageByFlashGoodsId(flashGoodsId);
        if(mv==null){
            return Result.error(CodeMsg.SERVER_ERROR);
        }else{
            List<FlashGoodsDetialMessageVo> list = new ArrayList<>();
            list.add(mv);
            return Result.success(list);
        }

    }

    //创建隐藏路径
    @RequestMapping(value = "bulidpath",method = RequestMethod.POST)
    @ResponseBody
    public Result<String> bulidPath(@RequestParam(value = "userId",defaultValue = "0") Integer userId,@RequestParam(value = "flashgoodsId",defaultValue = "0") Integer flashgoodsId){
        if(userId==0||flashgoodsId==0){
            return Result.error(CodeMsg.REQUEST_ILLEGAL);
        }
        String path = flashGoodsService.bulidPath(userId,flashgoodsId);
        List<String> list = new ArrayList<>();
        list.add(path);
        return Result.success(list);
    }

    //秒杀进行中。。。。。。。
    @RequestMapping(value = "{path}/bulidpath",method = RequestMethod.POST)
    @ResponseBody
    public Result<Integer> goingFlash(@PathVariable("path")String path, OrderMessageVo omv) {
        //判断请求数据异常
        if(omv == null|| omv.getUserid()<=0 || omv.getFlashgoodsid() <= 0 ){
            return Result.error(CodeMsg.REQUEST_ILLEGAL);
        }
        //判断秒杀是否在秒杀时段之内
        boolean judgeTime = flashGoodsService.judgeFlashGoodsTime(omv.getFlashgoodsid());
        if(!judgeTime){
            return Result.error(CodeMsg.FLASH_GOODS_NOT_IN_TIME);
        }

        //判断隐藏路径是否合法
        boolean flag = flashGoodsService.judgePath(omv.getUserid(),omv.getFlashgoodsid(),path);
        if(!flag){
            return Result.error(CodeMsg.REQUEST_ILLEGAL);
        }
        //一个用户访问次数的限制
        Integer visit =  redisService.get(FlashGoodsKey.getFlashVisitController,omv.getUserid()+":goingFlash"+omv.getFlashgoodsid(),Integer.class);
        if(visit != null && visit<=0){
            //一分钟之内的访问次数用完了，该方法限10次
            return  Result.error(CodeMsg.ACCESS_LIMIT_REACHED);
        }else{
            if(visit == null){
                redisService.set(FlashGoodsKey.getFlashVisitController,omv.getUserid()+":goingFlash"+omv.getFlashgoodsid(),10);
            }
            //访问次数减1
            redisService.decr(FlashGoodsKey.getFlashVisitController,omv.getUserid()+":goingFlash"+omv.getFlashgoodsid());
        }
        //判断用户是否已秒杀
        FlashOrder fo = redisService.get(FlashGoodsKey.getFlashGoodsOrder,omv.getUserid()+":"+omv.getFlashgoodsid(), FlashOrder.class);
       if(fo != null){
           return Result.error(CodeMsg.FLASH_GOODS_MIAOSHA);
       }
        //预减库存
        Integer num = redisService.get(FlashGoodsKey.getFlashGoodsStock,String.valueOf(omv.getFlashgoodsid()),Integer.class);
        //库存<0,则标记为N
        if(num < 0){
            return Result.error(CodeMsg.FLASH_GOODS_OVER);
       }else{
            redisService.decr(FlashGoodsKey.getFlashGoodsStock,String.valueOf(omv.getFlashgoodsid()));
        }
       //收货地址的拼接
        String receipAddress = provinceService.receipAddress(omv.getProvinceid(),omv.getCityid(),omv.getAreaid(),omv.getAddress());

        //入消息队列，格式转化
        FlashMessage fm = flashGoodsService.orderMessageVoReturnFlashMessage(omv,receipAddress);
        mqSender.sendFlashMessage(fm);
        //在排队中
        redisService.set(FlashGoodsKey.getSignFlashOrder,omv.getUserid()+":"+omv.getFlashgoodsid(),0);
        List<Integer> list = new ArrayList<>();
        list.add(0);
        return Result.success(list);
    }




    //轮询，查询用户的商品是否秒杀成功
    @RequestMapping(value = "getresult" , method = RequestMethod.POST)
    @ResponseBody
    public Result<String> getFlashResult(@RequestParam(value = "uid",defaultValue = "-1") Integer uid,@RequestParam(value = "fgid",defaultValue = "-1")Integer fgid){
        if(uid<1||fgid<1){
            return Result.error(CodeMsg.BIND_ERROR);
        }
       Integer num = redisService.get(FlashGoodsKey.getSignFlashOrder,uid+":"+fgid,Integer.class);
        List<String> list = new ArrayList<>();
       if(num == null){
            return Result.error(CodeMsg.ORDER_NOT_EXIST);
        }else if(num == 0){//秒杀排队中
           list.add("0");
            return Result.success(list);
        }else if(num == 1){//秒杀成功
            FlashOrder f = redisService.get(FlashGoodsKey.getFlashGoodsOrder,uid+":"+fgid, FlashOrder.class);
            String orderNum = f.getFlashorderid()+"";
            list.add(orderNum);
            return Result.success(list);
        }else{//秒杀失败
            return  Result.error(CodeMsg.MIAOSHA_FAIL);
        }
    }


}
